//
//  RTManager.m
//  GLUZ
//
//  Created by GS on 2025/2/18.
//

#import "RTManager.h"
#import "CryptoHelper.h"
@interface RTManager()<SRWebSocketDelegate>
@property (nonatomic, strong) SRWebSocket *webSocket;

@end
@implementation RTManager

- (void)connectWebSocket {
    // 科大讯飞 接口调用流程
    // https://www.xfyun.cn/doc/asr/rtasr/API.html#接口调用流程
    NSString *appid = @"9b1b2dfd";
    NSString *apiKey = @"e7590b1bc5a3de12928515f19e912356";
    
    NSString *timeInterval = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]];
    NSLog(@"当前时间戳 %@", timeInterval);
    // 1. 计算 baseString
    NSString *baseString = [NSString stringWithFormat:@"%@%@", appid, timeInterval];
    NSLog(@"baseString: %@", baseString);
    
    // 2. 计算 MD5
    NSString *md5String = [CryptoHelper md5Hash:baseString];
    NSLog(@"MD5: %@", md5String);
    
    // 3. HMAC-SHA1 加密 & Base64 编码
    NSString *signa = [CryptoHelper hmacSHA1:md5String key:apiKey];
    NSLog(@"signa: %@", signa);
    
    // 4. URL 编码
    //    NSString *urlString =[NSString stringWithFormat:@"ws://rtasr.xfyun.cn/v1/ws?appid=%@&ts=%@&signa=%@&lang=%@&transType=normal&transStrategy=2&targetLang=%@", appid, timeInterval, signa, self.lang, self.targetLang];
    NSString *urlString =[NSString stringWithFormat:@"ws://rtasr.xfyun.cn/v1/ws?appid=%@&ts=%@&transStrategy=2&signa=%@&lang=%@", appid, timeInterval, signa, self.lang];
    
    NSLog(@"url: %@", urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    
    self.webSocket = [[SRWebSocket alloc] initWithURL:url];
    self.webSocket.delegate = self;
    [self.webSocket open];
}

#pragma mark - SRWebSocketDelegate

// WebSocket 连接成功
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
    NSLog(@"WebSocket 连接成功");
}


// 发送音频数据（每40ms发送1280字节）
- (void)sendAudioData:(NSData *)audioData {
    if (self.webSocket.readyState == SR_OPEN) {
        NSError *error = nil;
        BOOL success = [self.webSocket sendData:audioData error:&error];
        if (!success) {
            NSLog(@"Failed to send audio data: %@", error.localizedDescription);
        }else{
            
        }
    } else {
        //NSLog(@"WebSocket is not open. Cannot send audio data.");
    }
}

// 发送结束标识 {"end": true}
//- (void)sendEndMessage {
//    if (self.webSocket.readyState == SR_OPEN) {
//        NSDictionary *endMessage = @{@"end": @YES};
//        NSError *error = nil;
//
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:endMessage options:0 error:&error];
//        if (error) {
//            NSLog(@"Failed to serialize end message: %@", error.localizedDescription);
//            return;
//        }
//
//        BOOL success = [self.webSocket sendData:jsonData error:&error];
//        if (!success) {
//            NSLog(@"Failed to send end message: %@", error.localizedDescription);
//        } else {
//            NSLog(@"Sent end message successfully.");
//        }
//    } else {
//        NSLog(@"WebSocket is not open. Cannot send end message.");
//    }
//}

// 收到消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    // NSLog(@"收到消息: %@", message);
    // 转换为 NSString 类型
    NSString *msg = (NSString *)message;
    
    // 解析 JSON
    NSError *jsonError = nil;
    NSDictionary *msgDict = [NSJSONSerialization JSONObjectWithData:[msg dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
    if (jsonError) {
        NSLog(@"JSON 解析错误: %@", jsonError.localizedDescription);
        return;
    }
    
    // 获取 action 类型
    NSString *action = msgDict[@"action"];
    
    // 根据 action 处理不同逻辑
    if ([action isEqualToString:@"started"]) {
        // 握手成功
        NSString *sid = msgDict[@"sid"];
        NSLog(@"握手成功！sid: %@",sid);
        
    } else if ([action isEqualToString:@"result"]) {
        // 处理转写结果
        NSString *data = msgDict[@"data"];
        // [self handleTranscriptionMessage:data];
        [self handleTranscriptionMiddleMessage:data];
        
    } else if ([action isEqualToString:@"error"]) {
        // 处理错误
        NSLog(@"Error: %@", msg);
    }
}

// 解析最终结果
- (void)handleTranscriptionMessage:(NSString *)jsonString {
    // 解析内层 JSON
    NSError *error = nil;
    NSData *nestedData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *nestedDict = [NSJSONSerialization JSONObjectWithData:nestedData options:0 error:&error];
    
    if (!nestedDict || error) {
        NSLog(@"解析内层 JSON 失败: %@", error.localizedDescription);
        return ;
    }
    
    // 打印解析结果
    NSString *src = nestedDict[@"src"];
    NSString *dst =  nestedDict[@"dst"];
    //    NSLog(@"源文本: %@", src);
    //    NSLog(@"翻译文本: %@", dst);
    //    NSLog(@"段落 ID: %@", nestedDict[@"segId"]);
    //    NSLog(@"开始时间: %@", nestedDict[@"bg"]);
    //    NSLog(@"结束时间: %@", nestedDict[@"ed"]);
    // 需要发送结束消息（目前没有发送所以结果始终是NO）
    //    NSLog(@"是否结束: %@", nestedDict[@"isEnd"] ? @"YES" : @"NO");
    if (src == nil  || dst == nil) {
        return;
    }
    if ([self.eventHandler respondsToSelector:@selector(onRecognizedText:translatedText:)] && dst &&dst) {
        [self.eventHandler onRecognizedText:src translatedText:dst];
    }
}

// 解析中间结果
- (void)handleTranscriptionMiddleMessage:(NSString *)jsonString {
    NSError *error = nil;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    
    if (error) {
        NSLog(@"JSON Parsing Error: %@", error.localizedDescription);
        return;
    }
    NSDictionary *stDic = jsonDict[@"cn"][@"st"];
    NSString *type = stDic[@"type"];
    if ([type isEqualToString:@"1"]) {
        // NSLog(@"中间过程，不处理");
        return;
    }
    NSArray *rtArray = stDic[@"rt"];
    NSMutableString *transcription = [NSMutableString string];
    
    for (NSDictionary *rt in rtArray) {
        NSArray *wsArray = rt[@"ws"];
        for (NSDictionary *ws in wsArray) {
            NSArray *cwArray = ws[@"cw"];
            for (NSDictionary *cw in cwArray) {
                NSString *word = cw[@"w"];
                NSString *wp = cw[@"wp"];
                if (![wp isEqualToString:@"p"]) {
                    // 标点符号 过滤掉
                    [transcription appendString:word];
                }
            }
        }
    }
    
    // 打印最终转写文本
    NSLog(@"Real-time Transcription: %@", transcription);
    
    if ([self.eventHandler respondsToSelector:@selector(onRecognizedText:translatedText:)]) {
        [self.eventHandler onRecognizedText:transcription translatedText:@""];
    }
}

// WebSocket 关闭 （调用 close 或超时后关闭）
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    NSLog(@"WebSocket 断开连接: %ld, 原因: %@", (long)code, reason);
    self.webSocket = nil;
    if ([self.eventHandler respondsToSelector:@selector(didCloseWithCode:reason:)]) {
        [self.eventHandler didCloseWithCode:code reason:reason];
    }
    // 重连
    [self reconnectWebSocket];
}

// WebSocket 连接失败
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    NSLog(@"WebSocket 连接失败: %@", error.localizedDescription);
    if ([self.eventHandler respondsToSelector:@selector(onError:)]) {
        [self.eventHandler onError:error];
    }
}

// 断线重连
- (void)reconnectWebSocket {
    [self.webSocket close];
    self.webSocket = nil;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self connectWebSocket];  // 1秒后重连
    });
}

// 关闭 WebSocket 连接
- (void)disconnectWebSocket {
    if (self.webSocket) {
        [self.webSocket close];
        self.webSocket = nil;
    }
}
@end
